package com.rs.caht.netty.chatdemo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

//聊天程序服务器端
@Component
public class WebSocketChatServer {

//    private int port; //服务器端端口号
//
//    public ChatServer(int port) {
//        this.port = port;
//    }

    public void run() throws Exception {
        //1.创建一个线程组：接收客户端连接
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        //2.创建一个线程组：处理网络IO操作
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            //3.创建服务器启动助手来配置参数
            ServerBootstrap b = new ServerBootstrap();
            //4.设置连个线程组
            b.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)//5.使用Nio对象作为服务端通道实现
                    .option(ChannelOption.SO_BACKLOG, 128)//6.设置线程队列等待连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true)//7.保持活动的连接状态
                    .childHandler(new webSocketInitializer());//8.创建一个初始化替代对象

            System.out.println("Netty Chat Server启动......");
            ChannelFuture f = b.bind(9005).sync();//b.bind 本身是异步的  sync使其同步等待
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
            System.out.println("Netty Chat Server关闭......");
        }
    }

//    public static void main(String[] args) throws Exception {
//        new ChatServer(9998).run();
//    }
}